/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitsolo.htm
 *
 * gitsolo is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitsolo.action.portal;

import java.io.IOException;

import org.zhiqim.git.Git;
import org.zhiqim.git.GitConstants;
import org.zhiqim.git.http.UploadHandler;
import org.zhiqim.gitsolo.Gitsolo;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.HttpResponse;
import org.zhiqim.httpd.context.core.Action;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;

/**
 * 上传包（客户端clone/fetch）
 *
 * @version v1.0.0 @author zouzhigang 2017-11-27 新建与整理
 */
public class UploadPackAction implements Action, GitConstants
{
    private static final Log log = LogFactory.getLog(UploadPackAction.class);
    
    @Override
    public void execute(HttpRequest request) throws Exception
    {
        HttpResponse response = request.getResponse();
        
        if (!UPLOAD_PACK_REQUEST_TYPE.equals(request.getContentType()))
        {//检查内容类型
            response.sendError(_415_UNSUPPORTED_MEDIA_TYPE_);
            return;
        }
        
        //请求正确，设置响应类型
        response.setContentTypeNoCharset(UPLOAD_PACK_RESULT_TYPE);
        
        //组装上传包数据
        Git git = (Git)request.getAttribute(GIT_ATTRIBUTE_REPOSITORY);
        UploadHandler handler = new UploadHandler(git);
        
        try
        {
            handler.execute(request.getInputStream(), response.getOutputStream());
        }
        catch (IllegalArgumentException e) 
        {
            Gitsolo.sendError(response, handler, "解析上传包失败:"+e.getMessage());
            log.error(e.getMessage());
        }
        catch (IOException e)
        {
            Gitsolo.sendError(response, handler, "处理上传包失败");
            log.error(e);
        }
        catch (Throwable e)
        {
            Gitsolo.sendError(response, handler, "处理上传包异常"+e.getMessage());
            log.error(e);
        }
    }
}
